<?

/* --|	IMAGE
  Software: Socially
  Version: 1.0
  Contact: http://socially.googlecode.com
  Info: http://socially.googlecode.com
  Support: http://socially.googlecode.com
  --------------------------------------------------------------------------
  Author: goker.cebeci | http://gokercebeci.com
  --------------------------------------------------------------------------
  License: Distributed under the GNU General Public License (GPL)
  http://www.gnu.org/licenses/gpl.html
  This program is distributed in the hope that it will be useful - WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.
  ------------------------------------------------------------------------- */

class image {

    public $image;
    public $imageFile;
    public $original;
    public static $logoFile = 'logo.png';
    public static $waterMarkFont = 'watermark.ttf';

    public function __construct($image) {
        //$this->image = $data;
        $source = @imagecreatefromstring($image);
        $w = @imagesx($source);
        if(!$w){
            // Find format
            $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
            // JPEG image
            $func = imagecreatefrom . (($ext == "jpg") ? 'jpeg' : $ext);
            $this->image = @$func($image);
        } else  $this->image = $source;
        /*
        if (!file_exists($this->imageFile)) {
            self::error('initialize', "File not found : '$this->imageFile'");
            return false;
        }
        $this->image = new imagick($this->imageFile);*/
        //return true;
        return $this->image;
    }

    public function check() {
        /* if(($this->image->getImageWidth() < 216) || ($this->image->getImageHeight() < 216)){  
          $this->kill();
          return 701; //uygunsuz format: resim olması gereken minimum değerlerden küçük.
          }
          if(abs($this->image->getImageWidth()/$this->image->getImageHeight()) > 2){
          $this->kill();
          return 702; //uygunsuz format: resimin en/boy oranı 2 den büyük, çok ince yada çok uzun resim.
          } */
        /*if (!$this->image->valid()) {
            $this->kill();
            return 703; //uygunsuz format: hatalı resim dosyası.
        }*/
        if (!$this->image) {
            return 703; //uygunsuz format: hatalı resim dosyası.
        }
        return 200;
    }

    public function resize($fileName, $width, $height, $options = array()) {
		// source image
        $image = $this->image;
        // Get dimensions
        $w = imagesx($image);
        $h = imagesy($image);
		// options                
        $options['method'] = $options['method'] ? $options['method'] : 'longside';
        $options['position'] = $options['position'] ? $options['position'] : 'center';
        $options['compress'] = $options['compress'] ? $options['compress'] : 75;
        // new size
        list ($new_width, $new_height) = self::getNewSize($w, $h, $width, $height, $options['method'] == 'crop' ? 'shortside' : $options['method']);
        //echo "SIZE: $new_width, $new_height<br>";
        // Resample
        $new = imagecreatetruecolor(round($new_width), round($new_height));
        imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
        
        if ($options['method'] == 'crop') {
        	if (isset($options['x']) || isset($options['y'])) {
                $x = $options['x'];
                $y = $options['y'];
            } else
                list ($x, $y) = self::getPosition($new_width, $new_height, $width, $height, $options['position']);
            //echo "CROP: 0, 0, $x, $y, $width, $height, $width, $height<br>";
            $crop = imagecreatetruecolor($width, $height);
            imagecopyresampled($crop, $new, 0, 0, $x, $y, $width, $height, $width, $height);
        }
		//echo 'NAME: '.$fileName.'.jpg'."<br>";
        // Enable interlancing [for progressive JPEG]
        imageinterlace($crop ? $crop : $new, true);
        // save image
        imagejpeg($crop ? $crop : $new, $fileName.'.jpg', $options['compress']);
    	// destroy data
        @imagedestroy($new);
        @imagedestroy($crop);
    }
    /*
    public function resize($fileName, $width, $height, $options = array()) {
        $options['method'] = $options['method'] ? $options['method'] : 'longside';
        $options['position'] = $options['position'] ? $options['position'] : 'center';
        $options['compress'] = $options['compress'] ? $options['compress'] : 75;
        $options['format'] = $options['format'] ? $options['format'] : 'jpeg';
        $options['progressive'] = $options['progressive'] ? $options['progressive'] : 1;

        $options['sharpen'] = $options['sharpen'] ? $options['sharpen'] : 0;
        $options['contrast'] = $options['contrast'] ? $options['contrast'] : 0;
        $options['logo'] = $options['logo'] ? $options['logo'] : 0;
        $options['logoFile'] = $options['logoFile'] ? $options['logoFile'] : $this->logoFile;
        $options['logoPosition'] = $options['logoPosition'] ? $options['logoPosition'] : 'bottomLeft';
        $options['waterMark'] = $options['waterMark'] ? $options['waterMark'] : 0;
        $options['waterMarkFont'] = $options['waterMarkFont'] ? $options['waterMarkFont'] : $this->waterMarkFont;
        $options['rotate'] = $options['rotate'] ? $options['rotate'] : 0;
        $this->initialize();
        if ($options['sharpen']) {
            $this->image->sharpenImage($options['sharpen'], 0);
        }
        if ($options['rotate']) {
            $this->image->rotateImage(new ImagickPixel('#000000'), $options['rotate']);
        }

        list ($w, $h) = self::getNewSize($this->image->getImageWidth(), $this->image->getImageHeight(), $width, $height, $options['method'] == 'crop' ? 'shortside' : $options['method']);
        $this->image->thumbnailImage($w, $h);

        if ($options['method'] == 'crop') {
            if (isset($options['x']) || isset($options['y'])) {
                $x = $options['x'];
                $y = $options['y'];
            }
            else
                list ($x, $y) = self::getPosition($w, $h, $width, $height, $options['position']);
            $this->image->cropImage($width, $height, $x, $y);
        }

        if ($options['contrast'])
            $this->image->contrastImage($options['contrast']);
        if ($options['logo']) {
            $logo = new imagick($options['logoFile']);
            list ($x, $y) = self::getPosition($w, $h, $logo->getImageWidth(), $logo->getImageHeight(), $options['logoPosition']);
            //echo $logo->getImageCompose().'-'.$x.' - '.$y;
            $this->image->compositeImage($logo, $logo->getImageCompose(), $x, $y);
        }
        if ($options['waterMark']) {
            $waterMark = new imagickDraw();
            $waterMark->setFont($options['waterMarkFont']);
            $waterMark->setFontSize(8.6);
            $waterMark->setFillColor(new ImagickPixel('#000000'));
            //$waterMark->pathLineToVerticalAbsolute(100);
            $waterMark->setTextAlignment(2);
            //$waterMark->setStrokeAntialias(0);
            $this->image->annotateImage($waterMark, (($this->image->getImageWidth()) / 2) + 1, (($this->image->getImageHeight()) - 6), 0, $options['waterMark']);
            $waterMark->setFillColor(new ImagickPixel('#f5f5f5'));
            $this->image->annotateImage($waterMark, (($this->image->getImageWidth()) / 2), (($this->image->getImageHeight()) - 7), 0, $options['waterMark']);
        }
        if ($options['progressive'])
            $this->image->setInterlaceScheme(Imagick::INTERLACE_PLANE);

        if ($options['compress'])
            $this->image->setCompressionQuality($options['compress']);
        if ($options['format'])
            $this->image->setImageFormat($options['format']);

        $this->save($fileName . '.jpg');
    }*/

    private function save($fileName) {
        if (!$this->image->writeImages($fileName, true)) {
            self::error('save', "File not save : '$imageFile'");
            return false;
        }
        return true;
    }

    /**
     * captcha function, session is must
     *
     * @param imageFile $bg
     * @param int $charCount
     */
    public static function captcha($bg, $font, $length = 4) {
        header('Content-type: image/png');
        header("Content-Disposition:inline ; filename=captcha.png");
        $captcha = imagecreatetruecolor(100, 45);
        $width = imagesx($captcha) - 4;
        $height = imagesy($captcha) - 4;
        $im = @imagecreate($width, $height);
        imagecolorallocate($im, 255, 255, 255);
        for ($i = 0; $i < ($width * $height) / 450; $i++) {
            imageline($im, rand(3, $width), rand(3, $height), rand(3, $width), rand(3, $height), imagecolorallocate($im, 205, 205, 222));
        }
        $possible = '23456789bcdfghjkmnpqrstvwxyz';
        $codeText = '';
        $i = 0;
        $left = 5;
        //$font = 'themes/' . THEME . '/fonts/captcha.ttf';
        while ($i < $length) {
            $codeText .= $codeChar = (rand(0, 10) > 5) ? substr($possible, rand(0, strlen($possible) - 1), 1) : (substr($possible, rand(0, strlen($possible) - 1), 1));
            $fontSize = $height * (rand(40, 60) / 100);
            imagettftext($im, $fontSize, rand(-21, 21), $left, $height * .8, imagecolorallocate($im, 69, 69, 69), $font, $codeChar);
            $left += $fontSize;
            $i++;
        }
        imagejpeg($im);
        imagedestroy($im);
        $_SESSION['CAPTCHA'] = $codeText;
        echo $captcha;
    }

    /*
      public function captcha($bg,$font,$charCount = 4){
      header('Content-type: image/jpeg');
      header("Content-Disposition:inline ; filename=secure.jpg");

      if(extension_loaded('imagick')){
      $captcha = new imagick($bg);

      $width = $captcha->getImageWidth()-8;
      $height = $captcha->getImageHeight()-8;

      $line = new imagickDraw();
      $line->setStrokeWidth(2);
      $line->setStrokeColor (new ImagickPixel('#cdcdde'));
      for( $i=0; $i<($width*$height)/450; $i++ ) {
      $line->line(rand(3,$width), rand(3,$height), rand(3,$width), rand(3,$height));
      }
      $captcha->drawImage($line);

      $possible = '23456789bcdfghjkmnpqrstvwxyz';
      $codeText = '';
      $i = 0;
      $left = 5;
      $code = new imagickDraw();
      while ($i < $charCount) {
      $codeText .= $codeChar = (rand(0,10)>5)?strtoupper(substr($possible, rand(0, strlen($possible)-1), 1)):(substr($possible, rand(0, strlen($possible)-1), 1));

      $fontSize = $height * (rand(50,70)/100);

      $code->setFont($font);
      $code->setFontSize($fontSize);
      $code->setFillColor(new ImagickPixel('#dd'.rand(11,22).''.rand(11,22)));
      $code->setTextAlignment(1);
      $code->setStrokeWidth(2);
      $code->setStrokeColor (new ImagickPixel('#cc'.rand(11,22).'00'));


      $captcha->annotateImage($code, $left, 41, rand(-21,21), $codeChar);
      $left += $fontSize;
      $i++;
      }
      } else {
      $captcha = imagecreatefromgif($bg);

      $width = imagesx($captcha)-8;
      $height = imagesy($captcha)-8;

      $im=@imagecreate($width, $height);
      imagecolorallocate($im, 255, 255, 255);
      for( $i=0; $i<($width*$height)/450; $i++ ) {
      imageline($im, rand(3,$width), rand(3,$height), rand(3,$width), rand(3,$height), imagecolorallocate($im, 205, 205, 222));
      }
      $possible = '23456789bcdfghjkmnpqrstvwxyz';
      $codeText = '';
      $i = 0;
      $left = 5;
      $font = 'lib/captcha/captcha.ttf';
      while ($i < $charCount) {
      $codeText .= $codeChar = (rand(0,10)>5)?substr($possible, rand(0, strlen($possible)-1), 1):(substr($possible, rand(0, strlen($possible)-1), 1));

      $fontSize = $height * (rand(40,60)/100);

      imagettftext($im, $fontSize, rand(-21,21), $left, $height*.8, imagecolorallocate($im, 51, 51, 51), $font, $codeChar);
      $left += $fontSize;
      $i++;
      }
      imagejpeg($im);
      imagedestroy($im);
      }
      $_SESSION['captcha'] = $codeText;
      echo $captcha;

      }
     */

    public function size() {
        return array(imagesx($this->image), imagesy($this->image));
        //return array($this->image->getImageWidth(), $this->image->getImageHeight());
    }

    public function kill() {

        unset($this->image);
        unset($this->imageFile);
    }

    public static function getPosition($originalWidth, $originalHeight, $areaWidth, $areaHeight, $type = 'center') {
        switch ($type) {
            case 1:
            case 'topLeft':
                return array(0, 0);
                break;
            case 2:
            case 'top':
                return array(ceil(($originalWidth - $areaWidth) / 2), 0);
                break;
            case 3:
            case 'topRight':
                return array(($originalWidth - $areaWidth), 0);
                break;
            case 4:
            case 'left':
                return array(0, ceil(($originalHeight - $areaHeight) / 2));
                break;
            case 5:
            case 'center':
                return array(ceil(($originalWidth - $areaWidth) / 2), ceil(($originalHeight - $areaHeight) / 2));
                break;
            case 6:
            case 'right':
                return array(($originalWidth - $areaWidth), ceil(($originalHeight - $areaHeight) / 2));
                break;
            case 7:
            case 'bottomLeft':
                return array(0, ($originalHeight - $areaHeight));
                break;
            case 8:
            case 'bottom':
                return array(ceil(($originalWidth - $areaWidth) / 2), ($originalHeight - $areaHeight));
                break;
            case 9:
            case 'bottomRight':
                return array(($originalWidth - $areaWidth), ($originalHeight - $areaHeight));
                break;
        }
    }

    public static function getNewSize($originalWidth, $originalHeight, $width, $height, $type = 'shortside') {
    	
		//echo "$originalWidth, $originalHeight, $width, $height, $type";
        
		if ($width == 0 || $height == 0)
            return array($width, $height);
        if ($type == 'longside') {
            if ($originalWidth >= $width || $originalHeight >= $height) {
                if ($originalWidth / $originalHeight >= 1 && $type == 0) {

                    $h = ceil(($width / $originalWidth) * $originalHeight);
                    if ($height < $h && $type == 0) {
                        $width = ceil(($height / $originalHeight) * $originalWidth);
                    } else {
                        $height = $h;
                    }
                } else {

                    $w = ceil(($height / $originalHeight) * $originalWidth);
                    if ($width < $w && $type == 0) {
                        $height = ceil(($width / $originalWidth) * $originalHeight);
                    } else {
                        $width = $w;
                    }
                }
            } else {
                $width = $originalWidth;
                $height = $originalHeight;
            }
        } else {
            if ($originalWidth >= $width || $originalHeight >= $height) {
                if ($originalWidth / $originalHeight <= 1) {
                    $h = ceil(($width / $originalWidth) * $originalHeight);
                    if ($height > $h) {
                        $width = ceil(($height / $originalHeight) * $originalWidth);
                    } else {
                        $height = $h;
                    }
                } else {

                    $w = ceil(($height / $originalHeight) * $originalWidth);
                    if ($width > $w) {
                        $height = ceil(($width / $originalWidth) * $originalHeight);
                    } else {
                        $width = $w;
                    }
                }
            } else {
                $width = $originalWidth;
                $height = $originalHeight;
            }
        }

        return array($width, $height);
    }

    public static function error($func, $error) {
        echo "<p><strong style=\"color:#FF0000\">Error function -> $func:</strong> $error</p>\n";
    }

    public static function name($ID) {
        return sha1($ID . KEY);
    }

}

?>